package api

import (
	"context"
	"gorm.io/gorm"
	"myproject/backend/models"
	"myproject/backend/types"
	"myproject/backend/utils"
)

type AuthApi struct {
	Ctx context.Context
	db  *gorm.DB
}

func NewAuthApi(db *gorm.DB) *AuthApi {
	return &AuthApi{
		db: db,
	}
}

func (a *AuthApi) GetUserOrganList(username string) types.AuthGetUserOrganListResp {
	resp := types.AuthGetUserOrganListResp{}
	requestPayLoad := map[string]any{
		"username": username,
		"domValue": "storebms",
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/ras/base/getUserOrganList",
		Resp:   &resp,
		Body:   requestPayLoad,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

func (a *AuthApi) GetCaptcha() types.AuthCaptchaResp {
	resp := types.AuthCaptchaResp{}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "GET",
		Suffix: "/ras/base/getCaptcha",
		Resp:   &resp,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

func (a *AuthApi) Login(req types.AuthLoginReq) types.AuthLoginResp {
	resp := types.AuthLoginResp{}
	user := models.User{}
	if err := a.db.Model(&models.User{}).
		Where("username = ?", req.Username).
		First(&user).Error; err != nil {
		resp.Code = types.FAIL
		resp.Msg = "数据库异常"
		return resp
	}
	if req.Password != user.Password {
		resp.Code = types.FAIL
		resp.Msg = "用户名或密码错误"
		return resp
	}
	utils.AuthToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjUwOCwidXNlck5hbWUiOiIxOTkwMDAwMDAwMCIsInVuaXF1ZU51bWJlciI6IiIsInVzZXJBdHRyIjoie2RvbT00XHUwMDI2XHUwMDI2MT0zXHUwMDI2XHUwMDI2Mj02XHUwMDI2XHUwMDI2Mz04XHUwMDI2XHUwMDI2Nz0xNH0iLCJwaG9uZSI6IjE5OTAwMDAwMDAwIiwidXNlck5pY2tOYW1lIjoiMeWPt-WRmOW3pSIsIm9yZ2FuaXphdGlvbklkIjoyMjA2MzYsInBPcmdhbklkIjoyMjA2MzYsInN0b3JlT3JnYW5JZHMiOlsyMjA2MzZdLCJkb21WYWx1ZSI6InN0b3JlYm1zIiwib3JnYW5DbGFzc2lmaWNhdGlvbklkIjozLCJkZXBBbmRQb3MiOltdLCJCdWZmZXJUaW1lIjo4NjQwMCwiaXNzIjoieXR4YiIsImF1ZCI6WyJZVFhCIl0sImV4cCI6MTc1OTY0NjQxNywibmJmIjoxNzU5MDQwNjE3fQ.Gu8CIGw_nsu6RuL57OtmEjmo9jM-8DxpPT3I_zebSnY"
	return resp
}

func (a *AuthApi) SaveToken(token string) {
	utils.AuthToken = token
	return
}
